<template>
  <div class="user-profile">
    <div class="page-header">
      <h2 class="page-title">个人信息</h2>
      <el-button type="primary" @click="handleEdit" v-if="!isEditing">编辑信息</el-button>
      <div v-else>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </div>
    </div>
    
    <el-card class="profile-card" v-loading="loading">
      <div class="profile-content">
        <!-- 基本信息 -->
        <div class="info-section">
          <el-form
            ref="formRef"
            :model="formData"
            :rules="formRules"
            label-width="120px"
            :disabled="!isEditing"
          >
            <el-row :gutter="30">
              <el-col :span="12">
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="formData.name" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别" prop="gender">
                  <el-radio-group v-model="formData.gender">
                    <el-radio value="male">男</el-radio>
                    <el-radio value="female">女</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="30">
              <el-col :span="12">
                <el-form-item label="年龄" prop="age">
                  <el-input-number v-model="formData.age" :min="0" :max="150" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="身份证号" prop="idCard">
                  <el-input v-model="formData.idCard" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="30">
              <el-col :span="12">
                <el-form-item label="联系电话" prop="phone">
                  <el-input v-model="formData.phone" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="出生日期" prop="birthday">
                  <el-date-picker
                    v-model="formData.birthday"
                    type="date"
                    placeholder="选择出生日期"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="家庭住址" prop="address">
              <el-input v-model="formData.address" type="textarea" rows="2" />
            </el-form-item>
            
            <el-row :gutter="30">
              <el-col :span="12">
                <el-form-item label="紧急联系人" prop="emergencyContact">
                  <el-input v-model="formData.emergencyContact" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="紧急联系电话" prop="emergencyPhone">
                  <el-input v-model="formData.emergencyPhone" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="30">
              <el-col :span="12">
                <el-form-item label="与紧急联系人关系" prop="emergencyRelation">
                  <el-select v-model="formData.emergencyRelation" placeholder="请选择关系" style="width: 100%">
                    <el-option label="子女" value="子女" />
                    <el-option label="配偶" value="配偶" />
                    <el-option label="兄弟姐妹" value="兄弟姐妹" />
                    <el-option label="亲戚" value="亲戚" />
                    <el-option label="朋友" value="朋友" />
                    <el-option label="其他" value="其他" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="当前健康状况">
                  <el-input :value="getHealthStatusText(formData.currentHealthStatus)" readonly />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="30">
              <el-col :span="12">
                <el-form-item label="护理级别">
                  <el-input :value="getCareLevelText(formData.careLevel)" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="入院日期">
                  <el-input :value="formData.admissionDate ? formData.admissionDate.toLocaleDateString('zh-CN') : '未设置'" readonly />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="30">
              <el-col :span="12">
                <el-form-item label="房间号">
                  <el-input :value="formData.roomNumber || '未分配'" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="床位号">
                  <el-input :value="formData.bedNumber || '未分配'" readonly />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="30">
              <el-col :span="12">
                <el-form-item label="状态">
                  <el-input :value="getStatusText(formData.status)" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <!-- 占位 -->
              </el-col>
            </el-row>
            
            <el-form-item label="疾病史/既往病史" prop="healthStatus">
              <el-input v-model="formData.healthStatus" type="textarea" rows="3" />
            </el-form-item>
            
            <el-form-item label="过敏史" prop="allergies">
              <el-input v-model="formData.allergies" type="textarea" rows="2" />
            </el-form-item>
            
            <el-form-item label="正在服用的药物" prop="medications">
              <el-input v-model="formData.medications" type="textarea" rows="2" />
            </el-form-item>
            
            <el-form-item label="备注/特殊需求" prop="specialNeeds">
              <el-input v-model="formData.specialNeeds" type="textarea" rows="2" />
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// API 基础URL
const API_BASE_URL = 'http://localhost:8080/api'

const isEditing = ref(false)
const loading = ref(false)
const formRef = ref()

// 获取当前用户ID
const getCurrentUserId = () => {
  try {
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      const userInfo = JSON.parse(userInfoStr)
      return userInfo.id
    }
    return null
  } catch (error) {
    console.error('获取用户ID失败:', error)
    return null
  }
}

// 根据用户ID获取老人信息
const getElderlyByUserId = async (userId: number) => {
  try {
    const response = await fetch(`${API_BASE_URL}/elderly/user/${userId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        return result.data
      }
    }
    throw new Error('未找到对应的老人信息')
  } catch (error) {
    console.error('获取老人信息失败:', error)
    throw error
  }
}

const formData = reactive({
  id: null as number | null,
  userId: null as number | null,
  name: '',
  gender: '',
  age: 0,
  idCard: '',
  phone: '',
  birthday: null as Date | null,
  address: '',
  emergencyContact: '',
  emergencyPhone: '',
  emergencyRelation: '',
  currentHealthStatus: '',
  careLevel: '',
  admissionDate: null as Date | null,
  roomNumber: '',
  bedNumber: '',
  status: '',
  healthStatus: '',
  allergies: '',
  medications: '',
  specialNeeds: ''
})

const originalData = ref({})

// 加载老人信息
const loadElderlyInfo = async () => {
  loading.value = true
  try {
    const userId = getCurrentUserId()
    if (!userId) {
      ElMessage.error('请先登录')
      return
    }
    
    const elderlyData = await getElderlyByUserId(userId)
    
    console.log('从后端获取的老人数据:', elderlyData)
    
    // 映射数据到表单
    Object.assign(formData, {
      id: elderlyData.id,
      userId: elderlyData.userId,
      name: elderlyData.name || '',
      gender: elderlyData.gender === '男' ? 'male' : 'female',
      age: elderlyData.age || 0,
      idCard: elderlyData.idCard || '',
      phone: elderlyData.phone || '',
      birthday: elderlyData.birthDate ? new Date(elderlyData.birthDate) : null,
      address: elderlyData.address || '',
      emergencyContact: elderlyData.emergencyContact || '',
      emergencyPhone: elderlyData.emergencyPhone || '',
      emergencyRelation: elderlyData.emergencyRelation || '',
      currentHealthStatus: elderlyData.healthStatus || '',
      careLevel: elderlyData.careLevel || '',
      admissionDate: elderlyData.admissionDate ? new Date(elderlyData.admissionDate) : null,
      roomNumber: elderlyData.roomNumber || '',
      bedNumber: elderlyData.bedNumber || '',
      status: elderlyData.status || '',
      healthStatus: elderlyData.medicalHistory || '',
      allergies: elderlyData.allergies || '',
      medications: elderlyData.medications || '',
      specialNeeds: elderlyData.remarks || ''
    })
    
    console.log('映射后的表单数据:', formData)
    
  } catch (error) {
    console.error('加载个人信息失败:', error)
    ElMessage.error('加载个人信息失败')
  } finally {
    loading.value = false
  }
}

const formRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  birthday: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入家庭住址', trigger: 'blur' }
  ],
  emergencyContact: [
    { required: true, message: '请输入紧急联系人', trigger: 'blur' }
  ],
  emergencyPhone: [
    { required: true, message: '请输入紧急联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  emergencyRelation: [
    { required: true, message: '请选择与紧急联系人关系', trigger: 'change' }
  ]
}

const handleEdit = () => {
  isEditing.value = true
  // 保存原始数据
  originalData.value = JSON.parse(JSON.stringify(formData))
}

const handleCancel = () => {
  isEditing.value = false
  // 恢复原始数据
  Object.assign(formData, originalData.value)
}

const handleSave = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
    
    loading.value = true
    
    // 准备提交数据，映射回后端字段
    const submitData = {
      userId: formData.userId,
      name: formData.name,
      gender: formData.gender === 'male' ? '男' : '女',
      age: formData.age,
      idCard: formData.idCard,
      phone: formData.phone,
      birthDate: formData.birthday ? formData.birthday.toISOString().split('T')[0] : null,
      address: formData.address,
      emergencyContact: formData.emergencyContact,
      emergencyPhone: formData.emergencyPhone,
      emergencyRelation: formData.emergencyRelation,
      medicalHistory: formData.healthStatus,
      allergies: formData.allergies,
      medications: formData.medications,
      remarks: formData.specialNeeds,
      // 保留管理员专用字段的原始值，避免被清空
      healthStatus: formData.currentHealthStatus,
      careLevel: formData.careLevel,
      admissionDate: formData.admissionDate ? formData.admissionDate.toISOString().split('T')[0] : null,
      roomNumber: formData.roomNumber,
      bedNumber: formData.bedNumber,
      status: formData.status
    }
    
    console.log('准备提交的数据:', submitData)
    console.log('提交URL:', `${API_BASE_URL}/elderly/${formData.id}`)
    
    const response = await fetch(`${API_BASE_URL}/elderly/${formData.id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(submitData)
    })
    
    if (!response.ok) {
      throw new Error('保存失败')
    }
    
    const result = await response.json()
    if (result.code === 200) {
      isEditing.value = false
      ElMessage.success('个人信息保存成功！')
      // 重新加载数据
      await loadElderlyInfo()
    } else {
      ElMessage.error(result.message || '保存失败')
    }
  } catch (error) {
    console.error('保存个人信息失败:', error)
    ElMessage.error('保存个人信息失败')
  } finally {
    loading.value = false
  }
}

const getCareLevelText = (careLevel: string) => {
  switch (careLevel) {
    case 'LOW':
      return '低级护理'
    case 'MEDIUM':
      return '中级护理'
    case 'HIGH':
      return '高级护理'
    case 'INTENSIVE':
      return '重症护理'
    default:
      return '未知护理级别'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'ACTIVE':
      return '活跃'
    case 'INACTIVE':
      return '非活跃'
    case 'DISCHARGED':
      return '已出院'
    case 'ON_LEAVE':
      return '请假'
    default:
      return '未知状态'
  }
}

const getHealthStatusText = (status: string) => {
  switch (status) {
    case 'GOOD':
      return '良好'
    case 'FAIR':
      return '一般'
    case 'POOR':
      return '较差'
    case 'DANGEROUS':
      return '危险'
    case 'CRITICAL':
      return '病重'
    default:
      return '未知健康状况'
  }
}

onMounted(async () => {
  // 加载老人信息
  await loadElderlyInfo()
  // 保存初始数据
  originalData.value = JSON.parse(JSON.stringify(formData))
})
</script>

<style scoped>
.user-profile {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 500;
}

.profile-card {
  max-width: 1200px;
  margin: 0 auto;
}

.profile-content {
  display: flex;
  gap: 40px;
  align-items: flex-start;
}

.info-section {
  flex: 1;
  max-width: 900px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label {
  font-weight: 500;
  color: #333;
}

:deep(.el-input.is-disabled .el-input__inner) {
  background-color: #fff;
  border-color: #e4e7ed;
  color: #606266;
}

:deep(.el-textarea.is-disabled .el-textarea__inner) {
  background-color: #fff;
  border-color: #e4e7ed;
  color: #606266;
}

:deep(.el-radio.is-disabled) {
  color: #606266;
}

:deep(.el-input-number.is-disabled .el-input__inner) {
  background-color: #fff;
  border-color: #e4e7ed;
  color: #606266;
}

@media (max-width: 768px) {
  .profile-content {
    flex-direction: column;
    gap: 20px;
  }
}
</style> 